package com.eorchis.module.classplanapply.ui.controller;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.eorchis.constants.DeptConstants;
import com.eorchis.constants.RoleConstants;
import com.eorchis.core.service.IBaseService;
import com.eorchis.core.springext.mvc.SessionConstant;
import com.eorchis.core.ui.commond.ResultState;
import com.eorchis.core.ui.controller.AbstractBaseController;
import com.eorchis.module.ResultJson;
import com.eorchis.module.classplanapply.bean.ClassPlanApplyQueryBean;
import com.eorchis.module.classplanapply.bean.ClassPlanSignFormatBean;
import com.eorchis.module.classplanapply.bean.export.ClassPlanSignExport;
import com.eorchis.module.classplanapply.bean.export.ClassPlanSignSheet;
import com.eorchis.module.classplanapply.service.IClassPlanApplyService;
import com.eorchis.module.classplanapply.ui.commond.ClassPlanApplyQueryCommond;
import com.eorchis.module.classplanapply.ui.commond.ClassPlanApplyValidCommond;
import com.eorchis.module.classuser.service.IClassUserService;
import com.eorchis.module.department.domain.Department;
import com.eorchis.module.remind.domain.Remind;
import com.eorchis.module.remind.service.IRemindService;
import com.eorchis.module.role.domain.Role;
import com.eorchis.module.trainingclass.querybean.TrainingClassQueryBean;
import com.eorchis.module.trainingclass.service.ITrainingClassService;
import com.eorchis.module.trainingclass.ui.commond.TrainingClassQueryCommond;
import com.eorchis.module.trainingclass.ui.commond.TrainingClassValidCommond;
import com.eorchis.util.excel.ExcelImportResult;
import com.eorchis.utils.BeanUtils;
import com.eorchis.utils.JSONUtils;
import com.eorchis.utils.excelutil.ExcelIO;
import com.eorchis.utils.excelutil.ExcelIOFactory;
import com.eorchis.utils.excelutil.export.bo.Sheet;
import com.eorchis.utils.utils.PropertyUtil;

/**
 * Title: ClassPlanApplyController<br>
 * Description: 班级计划报名管理控制器<br>
 * Company: GoldGov<br>
 * Copyright @ 2012 GoldGov .All rights reserved.<br>
 * 
 * @author SHQ
 * @createDate 2016-01-05
 * @version $Revision$
 */
@Controller("classPlanApplyController")
@RequestMapping(value = ClassPlanApplyController.MODULE_PATH)
public class ClassPlanApplyController extends AbstractBaseController<ClassPlanApplyValidCommond, ClassPlanApplyQueryCommond> {
	// 模块页面根路径
	public static final String MODULE_PATH = "/module/classplanapply";
	// 班级计划报名接口
	@Autowired
	@Qualifier("com.eorchis.module.classplanapply.service.impl.ClassPlanApplyServiceImpl")
	private IClassPlanApplyService classPlanApplyService;

	// 培训班用户关系接口
	@Resource(name = "com.eorchis.module.classuser.service.impl.ClassUserServiceImpl")
	private IClassUserService classUserService;

	// 培训班信息接口
	@Autowired
	@Qualifier("com.eorchis.module.trainingclass.service.impl.TrainingClassServiceImpl")
	private ITrainingClassService trainingClassService;
	
	// 提醒表接口
	@Resource(name = "com.eorchis.module.remind.service.impl.RemindServiceImpl")
	private IRemindService remindService;
		
	Log logger = LogFactory.getLog(ClassPlanApplyController.class);

	public IBaseService getService() {
		return classPlanApplyService;
	}

	public String getModulePath() {
		return MODULE_PATH;
	}

	public String getPageBasePath() {
		return "/portal/project/module/classplanapply";
	}

	/**
	 * @category 批量更新班级报名调整名额
	 * @param planApplyIds
	 * @param asignCounts
	 * @param request
	 * @param response
	 * @param resultState
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("batchAssignClassUserCount")
	public String batchAssignClassUserCount(String[] planApplyIds,String[] asignCityCounts,String[] asignCountyCounts,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception{
		resultState.setState(ResultState.RESULT_STATE_FAIL);
		resultState.setMessage("");
		Integer []AsignCounts=new Integer[2];
		try {
			if(planApplyIds!=null&&asignCityCounts!=null&&asignCountyCounts!=null){
				for (int i = 0; i < planApplyIds.length; i++) {
					ClassPlanApplyValidCommond commond = classPlanApplyService.find(planApplyIds[i]);
					AsignCounts[0]=commond.getAsignCityCount();
					AsignCounts[1]=commond.getAsignCountyCount();
					if(PropertyUtil.objectNotEmpty(asignCityCounts)){
						commond.setAsignCityCount(Integer.parseInt(asignCityCounts[i]));
					}
					if(PropertyUtil.objectNotEmpty(asignCountyCounts)){
						commond.setAsignCountyCount(Integer.parseInt(asignCountyCounts[i]));
					}
					commond.setAsignCount(commond.getAsignCityCount()+commond.getAsignCountyCount());
					classPlanApplyService.update(commond);
					
					try{
						if(!AsignCounts[0].equals(Integer.parseInt(asignCityCounts[i]))||!AsignCounts[1].equals(Integer.parseInt(asignCountyCounts[i]))){
							/**
							 * 添加提醒
							 * @Date 2016-05-12
							 * @author RongSL
							 * @Params  提醒类型，培训班名称，承办部委名称，提醒分类
							 * */
							Department dep=(Department)request.getSession().getAttribute("currentScope");
							TrainingClassQueryCommond q=new TrainingClassQueryCommond();
							q.setSearchClassId(commond.getClassId());
							//向中组部推送提醒
							TrainingClassValidCommond tcvc=(TrainingClassValidCommond)trainingClassService.findList(q).get(0);
//							remindService.remindOperate(Remind.TZME,tcvc.getClassName(),dep.getDeptName(),commond.getDeptName(),"ZZB",Remind.PXB);
							//向地方管理员推送提醒
							if(!AsignCounts[0].equals(Integer.parseInt(asignCityCounts[i]))){							//市级名额调整
								remindService.remindOperate(Remind.TZME,tcvc.getClassName(),dep.getDeptName(),commond.getDeptName(),"市级",String.valueOf(AsignCounts[0]),asignCityCounts[i],commond.getClassId(),Remind.PXB);
							}
							if(!AsignCounts[1].equals(Integer.parseInt(asignCountyCounts[i]))){	//县级名额调整
								remindService.remindOperate(Remind.TZME,tcvc.getClassName(),dep.getDeptName(),commond.getDeptName(),"县级",String.valueOf(AsignCounts[1]),asignCountyCounts[i],commond.getClassId(),Remind.PXB);
							}
						}
					}catch(Exception e){
						System.out.println("调整名额提醒接口出错了！");
					}
				}
			}
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
			resultState.setMessage("更新成功");
			
		} catch (Exception e) {
			resultState.setMessage("更新失败");
			throw e;
		}
		return "";
	}
	/**
	 * @category 上传报名计划
	 * @param modle
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public String uploadPlanApply(Model modle, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ResultJson resultJson = new ResultJson();

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (MultipartFile multipartFile : fileMap.values()) {
			CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
			FileItem item = commonsMultipartFile.getFileItem();
			InputStream is = null;
			InputStream ist = null;
			try {
				is = item.getInputStream();
				//判断excel格式和内容是否正确
				ExcelImportResult result = classPlanApplyService.divideImportExcel(is,request);
				if(result.isResultSign()){
					ist = item.getInputStream();
					classPlanApplyService.importPlanApplyTb(ist);
					resultJson.setSuccess(true);
					resultJson.setMsg("导入成功");
				}else{
					resultJson.setSuccess(false);
					resultJson.setMsg(result.getErrorMessage().toString());
				}
			} catch (Exception e) {
				resultJson.setSuccess(false);
				resultJson.setMsg("导入失败，请联系管理员");
				logger.error("import planApply error。", e);
			}finally{
				if(is!=null){
					is.close();
				}
				if(ist!=null){
					ist.close();
				}
			}
		}
		response.setContentType("text/html;charset=UTF-8");
		response.getOutputStream().write(((JSONUtils.objToJson(resultJson)).getBytes("UTF-8")));
		return null;
	}
	/**
	 * @category 导出名额对比表
	 * @param queryCommond
	 * @param request
	 * @param response
	 * @param resultState
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="exportSignUserComparation")
	public String exportSignUserComparation(@ModelAttribute("resultList") TrainingClassQueryCommond queryCommond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception{
		ClassPlanSignExport export = new ClassPlanSignExport();
		Role currentRole = (Role)request.getSession().getAttribute(SessionConstant.CURRENT_ROLE);
		Department currentScope = (Department) request.getSession().getAttribute(SessionConstant.CURRENT_SCOPE);
		String roleCode = currentRole.getCode();
		if(RoleConstants.ROLE_CODE_BW_ADMIN.equals(roleCode)){//部委管理员
			queryCommond.setSearchMinistrieID(currentScope.getDeptID());
			//qCommond.setSearchMinistrieID("7498");
		}
		//根据查询条件查询汇总导出结果对象
		List<ClassPlanSignFormatBean> resultList = classPlanApplyService.findExportSignComparationList(queryCommond);
		if(resultList==null){
			response.getOutputStream().write((("<script>alert('您导出的班级没有设置计划名额');window.close();</script>").getBytes("GBK")));
		}else{
			export.setResutList(resultList);
			ClassPlanSignSheet sheet = new ClassPlanSignSheet(export,ClassPlanSignSheet.EXPORT_FORMAT_NAME_COMPARATION);
			Sheet[] sheetArray = new Sheet[] { sheet};// 导出Excel的Sheet集合
			ExcelIO excelio = ExcelIOFactory.getExcelIO();// Excel导出工具
			String title=sheet.getSheetName();
			response.setContentType("application/msexcel;charset=ISO8859-1");
			response.setHeader("Content-disposition", "attachment; filename=" + java.net.URLEncoder.encode(title, "UTF-8") + ".xls");
			OutputStream out = response.getOutputStream();
			excelio.exportExcel(out, "resumeExportStyle", sheetArray, false);
		}
		return null;
	}
	/**
	 * @category 导出计划名额表
	 * @param queryCommond
	 * @param request
	 * @param response
	 * @param resultState
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="exportSignUserPlan")
	public String exportSignUserPlan(@ModelAttribute("resultList") TrainingClassQueryCommond queryCommond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception{
		ClassPlanSignExport export = new ClassPlanSignExport();
		//根据查询条件查询汇总导出结果对象
		List<ClassPlanSignFormatBean> resultList = classPlanApplyService.findExportSignComparationList(queryCommond);
		if(resultList==null){
			response.getOutputStream().write((("<script>alert('您导出的班级没有设置计划名额');window.close();</script>").getBytes("UTF-8")));
		}else{
			export.setResutList(resultList);
			ClassPlanSignSheet sheet = new ClassPlanSignSheet(export,ClassPlanSignSheet.EXPORT_FORMAT_NAME_PLAN);
			Sheet[] sheetArray = new Sheet[] { sheet};// 导出Excel的Sheet集合
			ExcelIO excelio = ExcelIOFactory.getExcelIO();// Excel导出工具
			String title=sheet.getSheetName();
			response.setContentType("application/msexcel;charset=ISO8859-1");
			response.setHeader("Content-disposition", "attachment; filename=" + java.net.URLEncoder.encode(title, "UTF-8") + ".xls");
			OutputStream out = response.getOutputStream();
			excelio.exportExcel(out, "resumeExportStyle", sheetArray, false);
		}
		return null;
	}

	/**
	 * @category 查询班级的实际报名情况(报名调整和报名页面)(委托部委办班在线报名系统)
	 * @param commond
	 * @throws Exception 
	 * @author NingSS
	 * @return
	 */
	@RequestMapping(value="/findClassAsignCount")
	public String findClassAsignCount(@ModelAttribute("result") ClassPlanApplyValidCommond commond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception {
		resultState.setState(ResultState.RESULT_STATE_FAIL);//失败状态
		com.eorchis.module.security.cas.domain.Role currentRole = 
				(com.eorchis.module.security.cas.domain.Role) request.getSession().getAttribute(SessionConstant.CURRENT_ROLE);
		if(PropertyUtil.objectNotEmpty(currentRole)&&PropertyUtil.objectNotEmpty(currentRole.getCode())){
			String roleCode = currentRole.getCode();//获得角色编码
			ClassPlanApplyValidCommond result = new ClassPlanApplyValidCommond();//封装查询结果的类
			ClassPlanApplyQueryCommond queryCommond = new ClassPlanApplyQueryCommond();//传递查询条件的类
			queryCommond.setSearchClassId(request.getParameter("searchClassId"));//获得前端传过来的班级id
			if(RoleConstants.ROLE_CODE_DW_ADMIN.equals(roleCode)){//单位管理员(报名页面)
				com.eorchis.module.security.cas.domain.Department d = 
						(com.eorchis.module.security.cas.domain.Department) request.getSession().getAttribute(SessionConstant.CURRENT_SCOPE);
				queryCommond.setSearchDeptId(PropertyUtil.objectNotEmpty(d) ? d.getDeptID() : null);//获得单位管理员当前管理范围的id
			}else{//中组部管理员和部委管理员(报名调整页面)
				//如未选中任何单位，便按照省市自治区节点treepath查询
				if(PropertyUtil.objectNotEmpty(commond.getSearchDepId())){
					if((DeptConstants.SIGN_DEPT_ROOT_ID).equals(commond.getSearchDepId())){
						queryCommond.setSearchTreepath(DeptConstants.SIGN_DEPT_TREEPATH);
					}else{
						queryCommond.setSearchDeptId(commond.getSearchDepId());
					}					
				}else{
					queryCommond.setSearchTreepath(DeptConstants.SIGN_DEPT_TREEPATH);
				}
			}
			//调用service层查询
			if (PropertyUtil.objectNotEmpty(queryCommond.getSearchClassId())
					&& (PropertyUtil.objectNotEmpty(queryCommond.getSearchDeptId())
							||PropertyUtil.objectNotEmpty(queryCommond.getSearchTreepath()))) {
				result = classPlanApplyService.findClassAsignCount(queryCommond);
				BeanUtils.copyProperties(result, commond);
				resultState.setState(ResultState.RESULT_STATE_SUCCESS);//成功状态
			} else {
				resultState.setMessage("缺少参数!");
			}
		}else{
			resultState.setMessage("角色不正确!");
		}
		return "";
	}
	/**
	 * @category 查看名额
	 * @param queryCommond
	 * @throws Exception 
	 * @author NingSS
	 * @return
	 */
	@RequestMapping(value="/findClassPlanApplyQueryBeanList")
	public String findClassPlanApplyQueryBeanList(@ModelAttribute("result") ClassPlanApplyQueryCommond queryCommond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception {
		resultState.setState(ResultState.RESULT_STATE_FAIL);//失败状态
		if(PropertyUtil.objectNotEmpty(queryCommond.getSearchClassId())){
			List<ClassPlanApplyQueryBean> resultList=classPlanApplyService.findClassPlanApplyQueryBeanList(queryCommond);
			queryCommond.setResultList(resultList);
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);//成功状态
		}else{
			resultState.setMessage("未选中任何班级!");
		}
		return "";
	}

	/**
	 * @category 查询培训班计划名额
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author LongJZ
	 * @createDate 2016-1-29
	 */
	@RequestMapping(value="/findClassPlanApplyList")
	public String findClassPlanApplyList(@ModelAttribute("result") ClassPlanApplyQueryCommond queryCommond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception {
		resultState.setState(ResultState.RESULT_STATE_FAIL);//失败状态
		if (PropertyUtil.objectNotEmpty(queryCommond.getSearchClassId())) {
			List<ClassPlanApplyQueryBean> resultList=classPlanApplyService.findClassPlanApplyList(queryCommond);
			queryCommond.setResultList(resultList);
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);//成功状态
		} else
			resultState.setMessage("未选中任何班级!");
		return "";
	}
}
